package com.scau.yangsuiyu.estore.dababases.dao;

import com.scau.yangsuiyu.estore.dababases.entity.Buyer;
import com.scau.yangsuiyu.estore.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.query.QueryParameter;

/**
 * @author suiyu_yang
 * @description buyer的dao类
 * @date 2019-05-23 14:15
 * @email suiyu_yang@163.com
 */
public class BuyerDao {


    public void insert(Buyer buyer) {
        Session session = HibernateUtil.currentSession();
        Transaction transaction = session.beginTransaction();

        session.save(buyer);

        transaction.commit();
        HibernateUtil.closeSession();
        System.out.println(buyer.getId());
    }

    public void delete(Buyer buyer) {
        Session session = HibernateUtil.currentSession();
        Transaction transaction = session.beginTransaction();

        session.delete(buyer);

        transaction.commit();
        HibernateUtil.closeSession();
    }


    public void update(Buyer buyer) {
        Session session = HibernateUtil.currentSession();
        Transaction transaction = session.beginTransaction();

        session.update(buyer);

        session.flush();
        transaction.commit();
        HibernateUtil.closeSession();
    }

    public Buyer getBuyerById(Integer id) {
        Session session = HibernateUtil.currentSession();

        Buyer buyer = session.get(Buyer.class, id);
        HibernateUtil.closeSession();
        return buyer;
    }


    public Buyer getBuyerByPhone(String phone) {
        Session session = HibernateUtil.currentSession();

        String sql = "from Buyer buyer where buyer.phone = '" + phone + "' ";

        Buyer buyer = (Buyer) session.createQuery(sql).uniqueResult();
        HibernateUtil.closeSession();
        return buyer;
    }

    public Buyer getBuyerByEmail(String email) {
        Session session = HibernateUtil.currentSession();

        String sql = "from Buyer buyer where buyer.email = '" + email + "' ";

        Buyer buyer = (Buyer) session.createQuery(sql).uniqueResult();

        HibernateUtil.closeSession();
        return buyer;
    }

    public Buyer getBuyerByUsername(String username) {
        Session session = HibernateUtil.currentSession();

        String sql = "from Buyer buyer where buyer.username = '" + username + "' ";

        Buyer buyer = (Buyer) session.createQuery(sql).uniqueResult();
        HibernateUtil.closeSession();
        return buyer;
    }


}
